/**
 *
 */
import Util;
import OSS;
import OpenPlatform;
import OSSUtil;
import FileForm;
import Number;
import OpenApi;
import OpenApiUtil;
import EndpointUtil;

extends OpenApi;


init(config: OpenApi.Config){
  super(config);
  @endpointRule = 'regional';
  
  checkConfig(config);
  @endpoint = getEndpoint('imageaudit', @regionId, @endpointRule, @network, @suffix, @endpointMap, @endpoint);
}

function getEndpoint(productId: string, regionId: string, endpointRule: string, network: string, suffix: string, endpointMap: map[string]string, endpoint: string) throws: string{
  if (!Util.empty(endpoint)) {
    return endpoint;
  }
  
  if (!Util.isUnset(endpointMap) && !Util.empty(endpointMap[regionId])) {
    return endpointMap[regionId];
  }
  return EndpointUtil.getEndpointRules(productId, regionId, endpointRule, network, suffix);
}

model ScanImageRequest {
  scene?: [ string ](name='Scene', description='1', example='porn'),
  task?: [ 
    {
      dataId?: string(name='DataId', example='uuid-xxxx-xxxx-1234'),
      imageTimeMillisecond?: long(name='ImageTimeMillisecond', example='1'),
      imageURL?: string(name='ImageURL', example='http://xxx.xxx.com/xxx.jpg'),
      interval?: int32(name='Interval', example='1'),
      maxFrames?: int32(name='MaxFrames', example='1'),
    }
  ](name='Task', description='1'),
}

model ScanImageAdvanceRequest {
  scene?: [ string ](name='Scene', description='1', example='porn'),
  task?: [ 
    {
      dataId?: string(name='DataId', example='uuid-xxxx-xxxx-1234'),
      imageTimeMillisecond?: long(name='ImageTimeMillisecond', example='1'),
      imageURLObject?: readable(name='ImageURL', example='http://xxx.xxx.com/xxx.jpg'),
      interval?: int32(name='Interval', example='1'),
      maxFrames?: int32(name='MaxFrames', example='1'),
    }
  ](name='Task', description='1'),
}

model ScanImageResponseBody = {
  data?: {
    results?: [ 
      {
        dataId?: string(name='DataId', example='uuid-xxxx-xxx-1234'),
        imageURL?: string(name='ImageURL', example='http://xxx.xxx.xxx/xxx.jpg'),
        subResults?: [ 
          {
            frames?: [ 
              {
                rate?: float(name='Rate', example='89.85'),
                URL?: string(name='URL', example='http://xxx.xxx.com/xxx-0.jpg'),
              }
            ](name='Frames'),
            hintWordsInfoList?: [ 
              {
                context?: string(name='Context', example='abc'),
              }
            ](name='HintWordsInfoList'),
            label?: string(name='Label', example='normal'),
            logoDataList?: [ 
              {
                height?: float(name='Height', example='106'),
                name?: string(name='Name', example='abc'),
                type?: string(name='Type', example='TV'),
                width?: float(name='Width', example='106'),
                x?: float(name='X', example='140'),
                y?: float(name='Y', example='68'),
              }
            ](name='LogoDataList'),
            OCRDataList?: [ string ](name='OCRDataList', description='1'),
            programCodeDataList?: [ 
              {
                height?: float(name='Height', example='413.0'),
                width?: float(name='Width', example='402.0'),
                x?: float(name='X', example='11.0'),
                y?: float(name='Y', example='0.0'),
              }
            ](name='ProgramCodeDataList'),
            rate?: float(name='Rate', example='99.91'),
            scene?: string(name='Scene', example='ad'),
            sfaceDataList?: [ 
              {
                faces?: [ 
                  {
                    id?: string(name='Id', example='AliFace_0001234'),
                    name?: string(name='Name', example='abc'),
                    rate?: float(name='Rate', example='91.54'),
                  }
                ](name='Faces'),
                height?: float(name='Height', example='131'),
                width?: float(name='Width', example='97'),
                x?: float(name='X', example='49'),
                y?: float(name='Y', example='39'),
              }
            ](name='SfaceDataList'),
            suggestion?: string(name='Suggestion', example='block'),
          }
        ](name='SubResults'),
        taskId?: string(name='TaskId', example='img4wlJcb7p4wH4lAP3111111-123456'),
      }
    ](name='Results'),
  }(name='Data'),
  requestId?: string(name='RequestId', example='69B41AE8-1234-1234-1234-12D395695D2D'),
}

model ScanImageResponse = {
  headers: map[string]string(name='headers'),
  statusCode: int32(name='statusCode'),
  body: ScanImageResponseBody(name='body'),
}

async function scanImageWithOptions(request: ScanImageRequest, runtime: Util.RuntimeOptions): ScanImageResponse {
  Util.validateModel(request);
  var body : map[string]any = {};
  if (!Util.isUnset(request.scene)) {
    body['Scene'] = request.scene;
  }
  if (!Util.isUnset(request.task)) {
    body['Task'] = request.task;
  }
  var req = new OpenApi.OpenApiRequest{ 
    body = OpenApiUtil.parseToMap(body),
  };
  var params = new OpenApi.Params{
    action = 'ScanImage',
    version = '2019-12-30',
    protocol = 'HTTPS',
    pathname = '/',
    method = 'POST',
    authType = 'AK',
    style = 'RPC',
    reqBodyType = 'formData',
    bodyType = 'json',
  };
  return callApi(params, req, runtime);
}

async function scanImage(request: ScanImageRequest): ScanImageResponse {
  var runtime = new Util.RuntimeOptions{};
  return scanImageWithOptions(request, runtime);
}

async function scanImageAdvance(request: ScanImageAdvanceRequest, runtime: Util.RuntimeOptions): ScanImageResponse {
  // Step 0: init client
  var accessKeyId = @credential.getAccessKeyId();
  var accessKeySecret = @credential.getAccessKeySecret();
  var securityToken = @credential.getSecurityToken();
  var credentialType = @credential.getType();
  var openPlatformEndpoint = @openPlatformEndpoint;
  if(Util.isUnset(openPlatformEndpoint)) {
    openPlatformEndpoint ='openplatform.aliyuncs.com';
  }
  if(Util.isUnset(credentialType)) {
    credentialType ='access_key';
  }
  var authConfig = new OpenApi.Config{
    accessKeyId = accessKeyId,
    accessKeySecret = accessKeySecret,
    securityToken = securityToken,
    type = credentialType,
    endpoint = openPlatformEndpoint,
    protocol = @protocol,
    regionId = @regionId,
  };
  var authClient = new OpenPlatform(authConfig);
  var authRequest = new OpenPlatform.AuthorizeFileUploadRequest{
    product = 'imageaudit',
    regionId = @regionId,
  };
  var authResponse = new OpenPlatform.AuthorizeFileUploadResponse{};
  var ossConfig = new OSS.Config{
    accessKeySecret = accessKeySecret,
    type = 'access_key',
    protocol = @protocol,
    regionId = @regionId,
  };
  var ossClient : OSS = null;

  var fileObj = new FileForm.FileField{};
  var ossHeader = new OSS.PostObjectRequest.header{};
  var uploadRequest = new OSS.PostObjectRequest{};
  var ossRuntime = new OSSUtil.RuntimeOptions{};
  OpenApiUtil.convert(runtime, ossRuntime);
  var scanImageReq = new ScanImageRequest{};
  OpenApiUtil.convert(request, scanImageReq);

  if(!Util.isUnset(request.task)) {
    var i0 : integer = 0;
    for (var item0 : request.task) {
      if(!Util.isUnset(item0.imageURLObject)) {
        authResponse = authClient.authorizeFileUploadWithOptions(authRequest, runtime);
        ossConfig.accessKeyId = authResponse.body.accessKeyId;
        ossConfig.endpoint = OpenApiUtil.getEndpoint(authResponse.body.endpoint, authResponse.body.useAccelerate, @endpointType);
        ossClient = new OSS(ossConfig);

        fileObj = new FileForm.FileField{
          filename = authResponse.body.objectKey,
          content = item0.imageURLObject,
          contentType = '',
        };
        ossHeader = new OSS.PostObjectRequest.header{
          accessKeyId = authResponse.body.accessKeyId,
          policy = authResponse.body.encodedPolicy,
          signature = authResponse.body.signature,
          key = authResponse.body.objectKey,
          file = fileObj,
          successActionStatus = '201',
        };
        uploadRequest = new OSS.PostObjectRequest{
          bucketName = authResponse.body.bucket,
          header = ossHeader,
        };
        ossClient.postObject(uploadRequest, ossRuntime);
        var tmp : ScanImageRequest.task = scanImageReq.task[i0];
        tmp.imageURL = `http://${authResponse.body.bucket}.${authResponse.body.endpoint}/${authResponse.body.objectKey}`;
        i0 = Number.ltoi(Number.add(Number.itol(i0), Number.itol(1)));
      }
    }
  }
  var scanImageResp = scanImageWithOptions(scanImageReq, runtime);
  return scanImageResp;
}

model ScanTextRequest {
  labels?: [ 
    {
      label?: string(name='Label', example='ad'),
    }
  ](name='Labels', description='1'),
  tasks?: [ 
    {
      content?: string(name='Content'),
    }
  ](name='Tasks', description='1'),
}

model ScanTextResponseBody = {
  data?: {
    elements?: [ 
      {
        results?: [ 
          {
            details?: [ 
              {
                contexts?: [ 
                  {
                    context?: string(name='Context'),
                  }
                ](name='Contexts'),
                label?: string(name='Label', example='ad'),
              }
            ](name='Details'),
            label?: string(name='Label', example='ad'),
            rate?: float(name='Rate', example='99.91'),
            suggestion?: string(name='Suggestion', example='block'),
          }
        ](name='Results'),
        taskId?: string(name='TaskId', example='txt6Vh5Fv0DAFy5hgdVRt3pqf-1s82jj'),
      }
    ](name='Elements'),
  }(name='Data'),
  requestId?: string(name='RequestId', example='C7CD87E3-57A5-4E2F-8A44-809F3554692C'),
}

model ScanTextResponse = {
  headers: map[string]string(name='headers'),
  statusCode: int32(name='statusCode'),
  body: ScanTextResponseBody(name='body'),
}

async function scanTextWithOptions(request: ScanTextRequest, runtime: Util.RuntimeOptions): ScanTextResponse {
  Util.validateModel(request);
  var body : map[string]any = {};
  if (!Util.isUnset(request.labels)) {
    body['Labels'] = request.labels;
  }
  if (!Util.isUnset(request.tasks)) {
    body['Tasks'] = request.tasks;
  }
  var req = new OpenApi.OpenApiRequest{ 
    body = OpenApiUtil.parseToMap(body),
  };
  var params = new OpenApi.Params{
    action = 'ScanText',
    version = '2019-12-30',
    protocol = 'HTTPS',
    pathname = '/',
    method = 'POST',
    authType = 'AK',
    style = 'RPC',
    reqBodyType = 'formData',
    bodyType = 'json',
  };
  return callApi(params, req, runtime);
}

async function scanText(request: ScanTextRequest): ScanTextResponse {
  var runtime = new Util.RuntimeOptions{};
  return scanTextWithOptions(request, runtime);
}

